<template>
  <el-dialog title="修改商户" :visible.sync="dialogSeeVisible" :before-close="cancelDialog" >
    <el-form class="form" :model="dialogInfo" :rules="formRules" ref="shopUpdate">

      <el-form-item label="门店名称: " prop="name">
        <el-input v-model="dialogInfo.name" disabled></el-input>
      </el-form-item>
      <el-form-item label="门店简介: " prop="introduction">
        <el-input v-model="dialogInfo.introduction"></el-input>
      </el-form-item>
      <el-form-item label="人均消费: " prop="pricePerMan">
        <el-input v-model.number="dialogInfo.pricePerMan" type="number"></el-input>
      </el-form-item>
      <!--<el-form-item label="地址: " prop="address">-->
      <!--<el-input v-model="form.address">-->
      <!--<el-button slot="append" icon="el-icon-position" @click="findPosition"></el-button>-->
      <!--</el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="品类: " prop="categoryId">
        <el-select v-model="dialogInfo.categoryId" placeholder="请选择" :filterable="true">
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商户: " prop="sellerId">
        <el-select v-model="dialogInfo.sellerId" placeholder="请选择" :filterable="true">
          <el-option
            v-for="item in sellerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签: " prop="tags">
        <el-input v-model="dialogInfo.tags"></el-input>
      </el-form-item>
      <el-dialog :visible.sync="dialogMapVisible" :append-to-body="true">
        <b-map
               :formParent="dialogInfo"
               :dialogMapVisible="dialogMapVisible"
               @update:formParent="updateAddress"
               @update:dialogMapVisible="dialogMapVisibles">
        </b-map>
      </el-dialog>
      <el-form-item label="地址: " prop="address">
        <el-input v-model="dialogInfo.address" disabled>
          <el-button slot="append" icon="el-icon-position" @click="showMap"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="经度: " prop="latitude">
        <el-input v-model="dialogInfo.latitude" disabled></el-input>
      </el-form-item>
      <el-form-item label="维度: " prop="longitude">
        <el-input v-model="dialogInfo.longitude" disabled></el-input>
      </el-form-item>
      <el-form-item label="营业开始时间: " prop="startTime">
        <el-time-picker
          v-model="dialogInfo.startTime"
          value-format="HH:mm:ss"
          :picker-options="{
          selectableRange: '00:00:00 - 23:59:59'}"
          placeholder="请选择营业开始时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="营业结束时间: " prop="endTime">
        <el-time-picker
          v-model="dialogInfo.endTime"
          value-format="HH:mm:ss"
          :picker-options="{
          selectableRange: '00:00:00 - 23:59:59'}"
          placeholder="请选择营业结束时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="商户头像: ">
        <br>
        <el-upload
          ref="upload"
          name="img"
          action="http://localhost:8081/shop/update"
          list-type="picture-card"
          :headers="headers"
          :class="{hide:hideUpload}"
          :auto-upload=false
          :limit=limitCount
          :data="this.dialogInfo"
          :file-list="this.fileList"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleError"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="handleChange">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="updateRequest">确 定</el-button>
      <el-button @click="cancelDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import axios from 'axios'
  import BMap from "@/views/BMap/index";
  export default {
    name: "SellerSeeDialog",
    //父组件 传 过来的 值
    props: {
      dialogSeeVisible: {
        type: Boolean,
        default: false
      },
      dialogInfo: {
        type: Object,
        default: {}
      },
      fileList:{
        type: Array,
        default:[]
      },
      categoryOptions:{
        type:Array,
        default:{}
      },
      sellerOptions:{
        type:Array,
        default:{}
      },
    },
    watch: {
      //监听 弹窗显示， 可以用来写 请求接口
      dialogSeeVisible: function(newVal, oldVal) {
        if (newVal) {

        }
      },
      fileList:function (newVal, oldVal) {
        this.hideUpload = newVal.length >= this.limitCount;
      }
    },
    components: {BMap},
    data() {
      return {
        // 大图
        dialogImageUrl: '',
        limitCount:1,
        // 上传组件+号
        hideUpload: false,
        // 是否已经上替换了文件
        hadUpdateFile: false,
        headers:{Authorization: getToken()},
        dialogVisible: false,
        dialogMapVisible: false,
        formRules: {
          name: [{ required: true, message: '请输入门店名称',trigger: 'blur' }],
          pricePerMan:[
            { required: true, type: 'number', min: 1,message: '请输入人均消费价格（最低消费1元）',trigger: 'blur' }
          ],
          address:[{ required: true, message: '请输入门店地址',trigger: 'blur' }],
          latitude:[{ required: true, message: '经度不能为空',trigger: 'blur' }],
          longitude:[{ required: true, message: '维度不能为空',trigger: 'blur' }],
          categoryId:[{ required: true, message: '请选择品类',trigger: 'blur' }],
          tags:[{ required: true, message: '请输入标签',trigger: 'blur' }],
          startTime:[{ required: true, message: '请选择门店营业开始时间',trigger: 'blur' }],
          endTime:[{ required: true, message: '请选择门店营业结束时间',trigger: 'blur' }],
          sellerId:[{ required: true, message: '请选择商家',trigger: 'blur' }],
        },
      };
    },
    computed: {
      // 这里定义上传文件时携带的参数，即表单数据
      upData: function() {
        return this.form
      },

    },
    created() {},
    mounted() {},
    methods: {
      //修改父组件传过来的值
      cancelDialog() {
        this.$emit("update:dialogSeeVisible", false);
        this.$refs.upload.clearFiles();
      },
      dialogMapVisibles(v){
        this.dialogMapVisible=v;
      },
      updateAddress(v){
        this.form = v
      },
      updateRequest(){
        this.$refs.shopUpdate.validate((valid) => {
          if(valid){
            if (!this.hadUpdateFile){
                console.log(this.dialogInfo)
                let formData = new FormData();
                Object.keys(this.dialogInfo).forEach((key) => {
                  formData.append(key, this.dialogInfo[key]);
                });
                axios({
                url: "http://localhost:8081/shop/update",
                method: "post",
                data: formData,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                  "Authorization": getToken()
                }
                })
                .then(response => {
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  });
                  this.$emit("update:dialogSeeVisible", false);
                  this.$emit('search');
                })
                .catch(err => {
                  console.log(err);
                });
            }else{
              this.$refs.upload.submit();
            }
          }
        })
      },
      handleRemove(file, fileList) {
        this.hideUpload = fileList.length >= 1;
        console.log(file, fileList);
      },
      handleChange (files, fileList) {
        this.hadUpdateFile = true;
        this.hideUpload = fileList.length >= 1;
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleSuccess(response, file, fileList){
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        // 关闭父组件弹窗
        this.$emit("update:dialogSeeVisible", false);
        // 调用父组件方法
        this.$emit('search');
        // 清除上传文件
        this.$refs.upload.clearFiles();
      },
      handleError(err, file, fileList){
        this.$message({
          message: err,
          type: 'success'
        });
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isJPG&&!isPNG) {
          this.$message.error('上传图片只能是 JPG, PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        return (isJPG||isPNG) && isLt2M;
      },
      showMap(){
        this.dialogMapVisible =true;
      },
    }
  };
</script>

<style lang="scss">
  .form{
    padding: 0 10px;
  }
  .dialog-footer{
    text-align: center;
  }
  .hide .el-upload--picture-card {
    display: none;
  }

</style>
